import os
import sys
import ast
import redis

class RedisDB(object):
    
    def __init__(self, port=0, unix_socket=None, db_id=-1):
        assert port or unix_socket
        
        if db_id == -1:
            return None
        
        if not port:
            self.db_inst = redis.Redis(unix_socket_path=unix_socket, db=db_id)
        elif not unix_socket:
            self.db_inst = redis.Redis(port=port, db=db_id)
        else:
            self.db_inst = redis.Redis(unix_socket_path=unix_socket, port=port, db=db_id)
    
    def _set_value(self, key, value):
        return self.db_inst.setnx(key, [value])
    
    def _get_value(self, key):
        return self.db_inst.get(key)
        
    def _store_value(self, key, value):
        return self._force_set_value(key, value)
    
    def _force_set_value(self, key, value):
        return self.db_inst.set(key, [value])
    
    def _batch_set_values(self, keys_values={}):
        pipeline = self.db_inst.pipeline()
        
        for (key, value) in list(keys_values.items()):
            pipeline.setnx(key, [value])
        
        pipeline.execute()

    def _del_key(self, key):
        return self.db_inst.delete(key)
    
    def _batch_del_keys(self, keys=[]):
        pipeline = self.db_inst.pipeline()
        for key in keys:
            pipeline.delete(key)
        pipeline.execute()
    
    def _inc_value(self, key):
        return self.db_inst.incr(key)
    
    def _dec_value(self, key):
        return self.db_inst.decr(key)
    
    def _exists(self, key):
        return self.db_inst.exists(key)

    def _get_all(self):
        keys = [key.decode() for key in self.db_inst.keys()]
        all_items = {}
        for key in keys:
            all_items[key] = ast.literal_eval(self._get_value(key).decode())[0]
        return all_items